﻿/************************************************************/
///         *                *                  *         ///
///       ***              * * *                ***       ///
///     *****            * * * * *              *****     ///
///   *******          * * * * * * *            *******   ///
/// *********        * * * * * * * * *          ********* ///
///   *******          * * * * * * *            *******   ///
///     *****            * * * * *              *****     ///
///       ***              * * *                ***       ///
///         *                *                  *         ///
/************************************************************/

using CefSharp.WinForms;
using NewLife.Log;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.Integration;

namespace XsDown.Common
{
    /// <summary>
    /// HttpClientX
    /// 创建人：njazy
    /// 创建时间：2021/8/19 17:41:30
    /// </summary>
    class HttpClientX
    {
        private HttpClient httpClient;
        private static HttpClientX client = null;
        public static HttpClientX Instance
        {
            get
            {
                if (client == null)
                    client = new HttpClientX();
                return client;
            }
            set
            {
                client = value;
            }
        }
        WindowsFormsHost frmHost = null;
        public WindowsFormsHost FrmHost
        {
            get { return frmHost; }
            set
            {
                frmHost = value;
                frmHost.Child = browser;
            }
        }
        private HttpClientX()
        {
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            httpClient = new HttpClient(handler);
            browser = new ChromiumWebBrowser("http://www.biquge.info/") { Size = new System.Drawing.Size(800, 600) };
            // browser.LoadingStateChanged += Browser_LoadingStateChanged;
        }
        private string _HtmlStr = null;
        public string HtmlStr
        {
            get
            {
                return _HtmlStr;
            }
        }

        //private ChromiumWebBrowser Browser
        //{
        //    get => browser; set
        //    {
        //        browser = value;
        //        if (browser != null)
        //        {
        //            browser.LoadingStateChanged -= Browser_LoadingStateChanged;
        //            browser.LoadingStateChanged += Browser_LoadingStateChanged;
        //        }
        //    }
        //}

        bool state = false;
        private void Browser_LoadingStateChanged(object sender, CefSharp.LoadingStateChangedEventArgs e)
        {
            if (e.IsLoading)
            {
                state = false;
                return;
            }

            try
            {
                var frame = e.Browser.MainFrame;
                var context = frame.GetSourceAsync().Result;

                _HtmlStr = context;
                state = true;
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }

        }

        CefSharp.WinForms.ChromiumWebBrowser browser = null;


        public string GetHtml2(string url)
        {
            _HtmlStr = null;
            browser.Invoke(new Action(() =>
            {
                //browser.Address = url;
                browser.Load(url);
            }));

            return null;
        }

        /// <summary>
        /// 获取html
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public string GetHtml(string url, string encode = "GB2312")
        {
            GetHtml2(url);

            System.Threading.Thread.Sleep(200);
            while (browser.IsLoading)
            {
                System.Threading.Thread.Sleep(200);

            }
            System.Threading.Thread.Sleep(500);
            var frame = browser.GetBrowser().MainFrame;
            var context = frame.GetSourceAsync().Result;

            return context;
        }
        public string GetHtmlByClient(string url, string encode = "GB2312")
        {
            httpClient.DefaultRequestHeaders.Add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47");
            httpClient.DefaultRequestHeaders.Add("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
            var stream = httpClient.GetStreamAsync(url).Result;
            Encoding encoding = Encoding.UTF8;
            try
            {
                encoding = Encoding.GetEncoding(encode);
            }
            catch (Exception)
            {
                encoding = Encoding.UTF8;
            }
            using (StreamReader sr = new StreamReader(stream, encoding))
            {
                return sr.ReadToEnd();
            }
        }

    }
}
